package com.farm.common.security;

import cn.hutool.http.HttpStatus;
import com.farm.common.util.R;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@AllArgsConstructor
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException){
		R<String> result = new R<>();
		result.setMsg(authException.getMessage());
		result.setData(authException.getMessage());

		if (authException instanceof CredentialsExpiredException
				|| authException instanceof InsufficientAuthenticationException) {
			result.setMsg("用户凭证已过期");
		}

		if (authException instanceof UsernameNotFoundException) {
			result.setMsg("用户未找到或者不存在");
		}

		if (authException instanceof BadCredentialsException) {
			result.setMsg("客户端信息错误，Basic认证失败");
		}
		SecurityServletResponse.responseProcessing(httpServletRequest, httpServletResponse, result, HttpStatus.HTTP_UNAUTHORIZED);
    }


}
